package com.caine.io;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;

/**
 * @Author: CaineZhu
 * @Description: save content to file
 * @Date: Created in 10:05 2020/11/3
 * @Modified By:
 */
public class FileChannel01 {
    public static void main(String[] args) throws Exception {
        String filePath = "D:\\file.txt";
        String str = "FileChannel测试"+ System.lineSeparator()
                +"1234567"+System.lineSeparator()
                +"abcdefg"+System.lineSeparator()
                +"魑魅魍魉";
        FileOutputStream fileOutputStream = new FileOutputStream(filePath);
        FileChannel fileChannel = fileOutputStream.getChannel();
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        byteBuffer.put(str.getBytes(StandardCharsets.UTF_8));
        byteBuffer.flip();
        fileChannel.write(byteBuffer);
        fileChannel.close();

        FileInputStream fileInputStream = new FileInputStream(filePath);
        FileChannel channel = fileInputStream.getChannel();
        ByteBuffer readBuffer = ByteBuffer.allocate((int)new File(filePath).length());
        channel.read(readBuffer);
//        readBuffer.flip();
//        readBuffer.get(bytes);
        System.out.println(new String(readBuffer.array()));
        fileInputStream.close();


    }
}
